package com.ibm.cps.newmessage;

import java.util.ArrayList;
import java.util.HashMap;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.KryoSerializable;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ibm.cps.message.MessageFields;
import com.ibm.cps.message.validation.ValidatorUtil;
import com.ibm.util.JSONUtility;
import com.ibm.util.exception.CPSException;

public class BasicMetadata extends AbstractMetadata implements KryoSerializable {

	public BasicMetadata() {

	}

	public BasicMetadata(String input) throws CPSException {
		this(JSONUtility.fromObjectString(input));
	}

	public BasicMetadata(ObjectNode object) throws CPSException {
		super(object);
		JSONUtility.convertField2Array(object, MessageFields.PARENTPROCESSORS);
		ValidatorUtil.checkNotNull(MessageFields.PARENTPROCESSORS,
				object.get(MessageFields.PARENTPROCESSORS));
		String parentString = object.get(MessageFields.PARENTPROCESSORS)
				.toString();
		this.parentProcessors = JSONUtility.getArrayList(parentString);
		this.input = object.toString();
	}

	@Override
	public void write(Kryo kryo, Output output) {
		output.writeString(tenantid);
		output.writeString(processorid);
		output.writeString(processorType);
		output.writeString(groupid);
		output.writeString(source);
		kryo.writeObject(output, parentProcessors);
		output.writeString(input);
		kryo.writeObject(output, key2value);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void read(Kryo kryo, Input input) {
		tenantid = input.readString();
		processorid = input.readString();
		processorType = input.readString();
		groupid = input.readString();
		source = input.readString();
		parentProcessors = kryo.readObject(input, ArrayList.class);
		this.input = input.readString();
		key2value = kryo.readObject(input, HashMap.class);
	}

	@Override
	public String toString() {
		return "{\"BasicMetadata\":{\"tenantid\":\"" + tenantid
				+ "\", \"processorid\":\"" + processorid
				+ "\", \"processorType\":\"" + processorType
				+ "\", \"parentProcessors\":\"" + parentProcessors
				+ "\", \"input\":\"" + input + "\", \"key2value\":\""
				+ key2value + "\", \"groupid\":\"" + groupid
				+ "\", \"source\":\"" + source + "\"}}";
	}
}
